﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;

using UploadManager;
using UnityCore;

namespace MBBStoreClient
{
    public partial class frmLogViewer : Form
    {
        SynchronizeData sync = new SynchronizeData();
        readDetails path = new readDetails();
        DataTable exportStockLog = new DataTable();

        Threader t = new Threader();
        public frmLogViewer()
        {
            InitializeComponent();

            btnClose.Click += new EventHandler(btnClose_Click);
            panel2.EnabledChanged += new EventHandler(panel2_EnabledChanged);
            btnSearch.Click += new EventHandler(btnSearch_Click);

            chkDateSpec.Click += new EventHandler(chkDateSpec_Click);
            btnPrint.Click +=new EventHandler(btnPrint_Click);
            sync.ProcessCompleted += new UnityCore.CoreHandler(sync_ProcessCompleted);
            sync.ProcessError += new UnityCore.CoreHandler(sync_ProcessError);

        }

        void sync_ProcessError(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(msg);
            });
        }

        void sync_ProcessCompleted(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                switch (pcode)
                {
                    case "GetStores":
                        cmbStore.Items.AddRange(sync.stores);
                        
                        break;
                    case "ReadMany":
                        exportStockLog = sync.exportTables[0];
                        if (exportStockLog.Rows.Count > 0)
                        {
                         
                            grdLog.DataSource = extractStockLog();
                            
                        }
                        pnlMsg.Visible = false;
                        break;
                }

            });
        }

        void chkDateSpec_Click(object sender, EventArgs e)
        {
            if (chkDateSpec.Checked)
            {
                txtDate.Enabled = true;
            }
            else
            {
                txtDate.Enabled = false;
            }
        }

       
       
        void btnSearch_Click(object sender, EventArgs e)
        {
            
            pnlMsg.Visible = true;
            path.date = "";
            path.fileNames.Add("Stock Log");
            path.remNode = cmbStore.Text;
            sync.ReadMany(path);
            
        }

        void ControlState(bool state)
        {
            grpFilter.Enabled = state;
            grdLog.Enabled = state;
            if (state)
            {
                pnlMsg.Visible = false;
            }
            else
            {
                pnlMsg.Visible = true;
            }
        }
        
        DataTable extractStockLog()
        {
            DataTable dt = new DataTable();
            dt.Columns.Clear();
            dt.Rows.Clear();

            dt.Columns.Add("Date");
            dt.Columns.Add("User");
            dt.Columns.Add("Barcode");
            dt.Columns.Add("Amount");
            dt.Columns.Add("Unit");

            for (int i = 0; i < exportStockLog.Rows.Count; i++)
            {
                

                if (chkDateSpec.Checked == true)
                {
                    string testDate = exportStockLog.Rows[i]["fDate"].ToString();
                    DateTime _testDate = DateTime.Parse(testDate);
                    string finalDate = _testDate.ToShortDateString();
    
                    if (finalDate.Equals(txtDate.Text)
                        && exportStockLog.Rows[i]["fBarcode"].ToString().Contains(txtBarcode.Text)
                        && exportStockLog.Rows[i]["fUser"].ToString().Contains(txtUser.Text)
                        )
                    {

                        DataRow dr = dt.NewRow();
                        dr["Date"] = exportStockLog.Rows[i]["fDate"].ToString();
                        dr["User"] = exportStockLog.Rows[i]["fUser"].ToString();
                        dr["Barcode"] = exportStockLog.Rows[i]["fBarcode"].ToString();
                        dr["Amount"] = exportStockLog.Rows[i]["fAmount"].ToString();
                        dr["Unit"] = exportStockLog.Rows[i]["fUnit"].ToString();
                        dt.Rows.Add(dr);
                    }
                }
                else
                {
                    if (exportStockLog.Rows[i]["fBarcode"].ToString().Contains(txtBarcode.Text)
                        && exportStockLog.Rows[i]["fUser"].ToString().Contains(txtUser.Text))
                    {

                        DataRow dr = dt.NewRow();
                        dr["Date"] = exportStockLog.Rows[i]["fDate"].ToString();
                        dr["User"] = exportStockLog.Rows[i]["fUser"].ToString();
                        dr["Barcode"] = exportStockLog.Rows[i]["fBarcode"].ToString();
                        dr["Amount"] = exportStockLog.Rows[i]["fAmount"].ToString();
                        dr["Unit"] = exportStockLog.Rows[i]["fUnit"].ToString();
                        dt.Rows.Add(dr);
                    }
                }
                
            }
            
            return dt;
        }

        void panel2_EnabledChanged(object sender, EventArgs e)
        {
            if (!panel2.Enabled)
            {
                panel2.BackColor = Color.MidnightBlue;
            }
            else
            {
                panel2.BackColor = Color.RoyalBlue;
            }
        }
        void btnClose_Click(object sender, EventArgs e)
        {
            pnlForm.Dispose();
            this.Dispose();
        }
        public Panel PanelForm
        {
            get { return pnlForm; }
        }
        public void Initialize(string Title)
        {
            this.Select();
            lblText.Text = Title;
            sync.Stores();
            path.fileNames = new List<string>();
        }

        //printing
        int cnt = 0;
        int pp = 1;
        void btnPrint_Click(object sender, EventArgs e)
        {
            if (grdLog.Rows.Count > 0)
            {
                PrintDocument pd = new PrintDocument();
                pd.DocumentName = lblText.Text;
                pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
                PrintDialog pdlg = new PrintDialog();
                pdlg.Document = pd;
                if (pdlg.ShowDialog() == DialogResult.OK)
                {
                    PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                    ppdlg.Document = pd;
                    //Tracking.EnterLog("Price Table is printed.", DateTime.Now.ToString());
                    ppdlg.ShowDialog();
                }
            }
        }

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.MarginBounds.Left - 50;
            float rm = e.PageBounds.Width - 150;
            float bm = e.PageBounds.Height - 100;
            float ht = 0;
            Font cFont;
            StringFormat sf = new StringFormat();


            //Header
            y = 110;
            cFont = new Font("Courier New", 11f, FontStyle.Bold);
            ht = cFont.GetHeight(e.Graphics);
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString(cmbStore.Text, new Font("Courier New", 15f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 50, sf);
            
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Stock Log - Page " + pp, cFont, Brushes.Black, lm, y, sf);
            
            //Column Header
            y += ht;

            e.Graphics.FillRectangle(Brushes.LightGray, lm, y, rm - lm + 100, ht);
            e.Graphics.DrawRectangle(new Pen(Brushes.Black), lm, y, rm - lm + 100, ht);
            sf.Alignment = StringAlignment.Center;
            float cx = lm + (((rm - lm) * 30) / 100);
            float tx = lm + (((rm - lm) * 15f) / 100);
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Date", cFont, Brushes.Black, tx, y, sf);

            cx += ((rm - lm) * 30) / 100;
            tx = cx - ((rm - lm) * 30) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("User", cFont, Brushes.Black, tx, y, sf);

            cx += ((rm - lm) * 25) / 100;
            tx = cx - ((rm - lm) * 25) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Barcode", cFont, Brushes.Black, tx, y, sf);

            cx += ((rm - lm) * 18) / 100;
            tx = cx - ((rm - lm) * 18) / 200;
            //e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            //e.Graphics.DrawString("Check No: ", cFont, Brushes.Black, tx, y, sf);
            // cx += ((rm - lm) * 18) / 100;
            //tx = cx - ((rm - lm) * 18) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Amount", cFont, Brushes.Black, tx, y, sf);

            tx += ((rm - lm) * 17) / 100;
            e.Graphics.DrawString("Unit", cFont, Brushes.Black, tx, y, sf);
            //Data
            y += ht * (1.5f);
            cFont = new Font("Courier New", 11f, FontStyle.Regular);
            ht = cFont.GetHeight(e.Graphics);
            lpp = (bm - y) / ht;
            int cl = 0;
            float stx = 0;

            while (cl <= lpp && cnt < grdLog.Rows.Count)
            {
                sf.Alignment = StringAlignment.Near;
                stx = lm + 1;
                string str = grdLog.Rows[cnt].Cells[0].Value.ToString();
                if (str.Length > 20)
                {
                    str = str.Substring(0, 17) + "...";
                }
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                stx += ((rm - lm) * 30) / 100;
                str = grdLog.Rows[cnt].Cells[1].Value.ToString();
                if (str.Length > 23)
                {
                    str = str.Substring(0, 20) + "...";
                }
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                stx += ((rm - lm) * 30) / 100;
                
                str = grdLog.Rows[cnt].Cells[2].Value.ToString();
                if (str.Length > 18)
                {
                    str = str.Substring(0, 15) + "...";
                }
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                
                sf.Alignment = StringAlignment.Far;
                stx += ((rm - lm) * 37) / 100;

                //str = grdLog.Rows[cnt].Cells[3].Value.ToString();
                //e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                //stx += ((rm - lm) * 20) / 100;

                str = grdLog.Rows[cnt].Cells[3].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                stx += ((rm - lm) * 12) / 100;
                
                str = grdLog.Rows[cnt].Cells[4].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                y += ht;
                cnt++;
                cl++;
            }
            //e.Graphics.DrawString("Total", cFont, Brushes.Blue, stx - 150, y + 10, sf);
            //e.Graphics.DrawString(txtTotal.Text, cFont, Brushes.Blue, stx - 4, y + 10, sf);

            if (cnt < grdLog.Rows.Count)
            {
                e.HasMorePages = true;
                pp++;
            }
            else
            {
                e.HasMorePages = false;
                cnt = 1;
                pp = 1;
            }
        }

    }
}
